<?php
/**
 * Created by PhpStorm.
 * User: tingyugetc
 * Date: 16/12/23
 * Time: 下午10:23
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\Setting;
use App\Repositories\AgentRepository;
use App\Repositories\SettingRepository;
use Illuminate\Http\Request;
use Redirect;

class AgentController extends Controller
{

    public function getConfig() {
        $config = SettingRepository::getAgentSetting();
        return admin_view('agent/config', compact('config'));
    }

    public function postConfig(Request $request) {
        SettingRepository::setAgentSetting($request->get('service_year'), $request->get('share_expire'));
        return redirect(admin_url('agent/config'));
    }

    public function getAgents() {
        $agents = AgentRepository::getAllAgents();
//        dump($agentLists);
        return admin_view('agent/agents', compact('agents'));
    }

    public function getCreate() {
        return admin_view('agent/create');
    }

    public function postCreate(Request $request) {

        $password = $request->get('password');
        $repass = $request->get('repass');

        if ($password != $repass) {
            return Redirect::back()->withInput()->withErrors('密码不一致！');
        }

        $agent = new Agent();
        $agent->name = $request->get('name');
        $agent->wechat = $request->get('wechat');
        $agent->phone = $request->get('phone');
        $agent->address = $request->get('address');
        $agent->status = $request->get('status');
        $agent->id_number = $request->get('id_number');
        $agent->password = md5($request->get('password'));

        AgentRepository::addAgent($agent);
        return redirect(admin_url('agent/agents'));
    }

    public function getUpdate($id) {
        $agent = Agent::find($id);
        return admin_view('agent/create', compact('agent'));
    }

    public function postUpdate(Request $request, $id) {
        $agent = Agent::find($id);
        $agent->name = $request->get('name');
        $agent->wechat = $request->get('wechat');
        $agent->phone = $request->get('phone');
        $agent->address = $request->get('address');
        $agent->status = $request->get('status');
        $agent->id_number = $request->get('id_number');
        $agent->password = md5($request->get('password'));

        AgentRepository::addAgent($agent);
        return redirect(admin_url('agent/agents'));
    }

    public function getDestroy($id) {
        (new AgentRepository())->destroy($id);
        return redirect(admin_url('agent/agents'))->withMessage('删除成功');
    }

    public function getLevel() {
        return admin_view('agent/level');
    }


}